import api from '../../api';
import { apiModeUtils } from '../../apiConfig';

export interface PermissionCondition {
  id?: string;
  permissionId: string;
  field: string;
  operator: string;
  value?: string;
  contextField?: string;
  description?: string;
  type: 'user' | 'resource' | 'environment';
  status: number;
  sort?: number;
  priority?: number;
  conditionGroup?: string;
  tableName?: string;
  sqlExpression?: string; // 新增：完整SQL表达式，支持复杂权限逻辑
  enabled?: number; // 新增：启用状态：1-启用，0-禁用
}

export interface PermissionConditionQuery {
  permissionId?: string;
  field?: string;
  operator?: string;
  type?: string;
  status?: number;
  description?: string;
  tableName?: string;
  conditionGroup?: string;
  current?: number;
  size?: number;
}

export interface DataPermissionStats {
  totalPermissions: number;
  totalConditions: number;
  enabledConditions: number;
  disabledConditions: number;
  coveredTables: number;
  conditionGroups: number;
}

export interface DataPermissionTest {
  conditionId: string;
  userId?: number;
  tableName?: string;
  context?: Record<string, any>;
}

// 创建权限条件API包装器
const api_condition = apiModeUtils.createApi('permissionConditionApi', api, false);

/**
 * 权限条件API服务
 */
export const permissionConditionApi = {
  /**
   * 分页查询权限条件
   */
  page: (query: PermissionConditionQuery) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/page',
      method: 'POST',
      data: query,
    });
  },

  /**
   * 获取权限条件详情
   */
  get: (id: string) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/get/${id}`,
      method: 'GET',
    });
  },

  /**
   * 创建权限条件
   */
  create: (data: PermissionCondition) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/add',
      method: 'POST',
      data,
    });
  },

  /**
   * 更新权限条件
   */
  update: (data: PermissionCondition) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/update',
      method: 'PUT',
      data,
    });
  },

  /**
   * 删除权限条件
   */
  delete: (id: string) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/delete/${id}`,
      method: 'DELETE',
    });
  },

  /**
   * 根据权限ID获取权限条件列表
   */
  getByPermissionId: (permissionId: string) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/permission/${permissionId}`,
      method: 'GET',
    });
  },

  /**
   * 批量更新权限条件排序
   */
  batchUpdateSort: (conditionIds: string[]) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/batch-sort',
      method: 'PUT',
      data: conditionIds,
    });
  },

  /**
   * 验证权限条件
   */
  validateConditions: (permissionId: string, context: any) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/validate/${permissionId}`,
      method: 'POST',
      data: context,
    });
  },

  /**
   * 检查字段和操作符组合是否存在
   */
  checkFieldAndOperator: (params: {
    permissionId: string;
    field: string;
    operator: string;
    excludeId?: string;
  }) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/check-field',
      method: 'GET',
      params,
    });
  },

  /**
   * 根据权限ID删除所有条件
   */
  deleteByPermissionId: (permissionId: string) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/permission/${permissionId}`,
      method: 'DELETE',
    });
  },

  // === 数据权限管理相关功能 ===
  
  /**
   * 获取表权限配置统计
   */
  getTablePermissionStats: () => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/table-stats',
      method: 'GET',
    });
  },

  /**
   * 根据表名获取权限条件
   */
  getByTableName: (tableName: string) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/table/${tableName}`,
      method: 'GET',
    });
  },

  /**
   * 批量创建权限条件
   */
  batchCreateConditions: (params: {
    tableName: string;
    permissionCode: string;
    conditions: PermissionCondition[];
  }) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/batch-create',
      method: 'POST',
      params: {
        tableName: params.tableName,
        permissionCode: params.permissionCode,
      },
      data: params.conditions,
    });
  },

  /**
   * 获取用户数据权限SQL
   */
  getUserDataPermissionSql: (params: {
    userId: number;
    tableName: string;
    tableAlias?: string;
  }) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/user-sql',
      method: 'GET',
      params,
    });
  },

  /**
   * 清除权限条件缓存
   */
  clearPermissionConditionCache: (permissionCode?: string) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/clear-cache',
      method: 'DELETE',
      params: { permissionCode },
    });
  },

  /**
   * 获取权限条件统计信息
   */
  getPermissionConditionStats: (): Promise<DataPermissionStats> => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/stats',
      method: 'GET',
    });
  },

  /**
   * 导出权限条件配置
   */
  exportPermissionConditions: (tableName?: string) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/export',
      method: 'GET',
      params: { tableName },
      responseType: 'blob',
    });
  },

  /**
   * 导入权限条件配置
   */
  importPermissionConditions: (configData: any[]) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/import',
      method: 'POST',
      data: configData,
    });
  },

  /**
   * 测试权限条件
   */
  testPermissionCondition: (conditionId: string, testContext: Record<string, any>) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/test/${conditionId}`,
      method: 'POST',
      data: testContext,
    });
  },

  /**
   * 获取表权限映射配置
   */
  getTablePermissionMappings: () => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/table-mappings',
      method: 'GET',
    });
  },

  /**
   * 更新权限条件状态
   */
  updateConditionStatus: (conditionId: string, status: number) => {
    return api.request({
      url: `/system/api/v3/sys/permission-conditions/${conditionId}/status`,
      method: 'PUT',
      data: { status },
    });
  },

  /**
   * 获取权限条件执行日志
   */
  getConditionExecutionLogs: (params: {
    conditionId?: string;
    userId?: number;
    startTime?: string;
    endTime?: string;
    current?: number;
    size?: number;
  }) => {
    return api.request({
      url: '/system/api/v3/sys/permission-conditions/execution-logs',
      method: 'GET',
      params,
    });
  },
};